package com.example.excel.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Random;

@WebServlet(name = "CaptchaServlet", value = "/CaptchaServlet")
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Font RANDOM_FONT = new Font("Fixedsys", Font.PLAIN, 18);
    private static final int WIDTH = 100;
    private static final int HEIGHT = 30;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("image/jpeg");
        OutputStream outputStream = resp.getOutputStream();
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setFont(RANDOM_FONT);
        Random random = new Random();
        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        g.setColor(new Color(red, green, blue));
        String captchaText = generateCaptchaText();

        req.getSession().setAttribute("captcha", captchaText);

        g.drawString(captchaText, 10, 20);
        g.dispose();
        ImageIO.write(image, "jpeg", outputStream);
        outputStream.close();
    }

    private String generateCaptchaText() {
        Random random = new Random();
        StringBuilder captchaText = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            captchaText.append(random.nextInt(10)); // 添加一个随机数字到验证码文本中
        }
        return captchaText.toString();
    }
}